<template>
	<div class="chart-container">
		<Chart :type="chartType" 
		:data="data" 
		:autosize="true" 
		:chart-options="chartOptions"
		:series-options="seriesOptions"
		ref="lwChart" />
	</div>
	<div class="action-button">
		<select  @change="changeSymbol">
			<option value="BTCUSDT">BTC_USDT</option>
			<option value="ETHUSDT">ETH_USDT</option>
			<option value="SOLUSDT">SOL_USDT</option>
		</select>
		<select @change="changeInterval">
			<option value="1">1分钟</option>
			<option value="2">3分钟</option>
			<option value="3">5分钟</option>
			<option value="4">15分钟</option>
			<option value="5">30分钟</option>
			<option value="6">1小时</option>
			<option value="7">4小时</option>
			<option value="8">1日</option>
		</select>

		<button @click="nextLine">下一条k线</button>

	</div>
</template>

<script setup lang="ts">


import { ref, onMounted, } from 'vue';
import axios from 'axios';
import Chart from './components/Chart.vue';
import {CrosshairMode, type Time} from "lightweight-charts";

const chartType = ref('candlestick');
const lwChart = ref();
const    startTime = ref('');
const    endTime = ref('');


const chartOptions = ref({
  width: 1400,
  height: 600 ,
  //本地化设置
  localization:{
    dateFormat : "yyyy-MM-dd HH:mm:ss",
    //格式化时间
    timeFormatter:(timestamp:number)=>{
      const date = new Date(timestamp * 1000);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false // 使用24小时制
      });
    }

  },
  //十字光标
  crosshair:{
    mode: CrosshairMode.Normal,
  }
});
const seriesOptions = ref({ upColor: '#26a69a', downColor: '#ef5350', borderVisible: false, wickUpColor: '#26a69a', wickDownColor: '#ef5350' });
//声明为 Kline 属性
const resList : Kline[] = [];

let interval = ref(2);
let symbol   = ref('BTCUSDT');



//初始化 k 线 数据
async function getInitKlineData() {
	await axios.get('/tradingView/initKlines', {
		params: {
			interval: interval.value,
			symbol: symbol.value,
			startTime: startTime.value,
			endTime: endTime.value
		}
	}).then(function (res) {
		console.log('axios 获取到的数据', res.data.data)
		// data.value = res.data.data
		resList.length = 0;
		res.data.data.forEach(function (item: any) {
			resList.push(new Kline(Number(item.o), Number(item.h), Number(item.l), Number(item.c), Date.parse(item.periodStart)/1000))
		})

	}).catch(function (err) {
		console.log(err)
	}).finally(function () {
		console.log('finally')
	})
}

// 全局变量
let data : Kline[] = [];


onMounted(async () => {
	await initChart();
});



async function initChart() {
	await getInitKlineData();
	//赋值给 全局变量
	data = resList;
	// console.log('赋值前的dataValue----', data)
  if (resList.length == 0)
      alert('未获取到数据，请先手动刷新出数据再说')
	//重新赋值给 图表
	lwChart.value.changeData(resList);
	// console.log('赋值后的dataValue', data)
}

function formatTime(time: number){
  let dd = new Date(time * 1000);

  return  dd.toLocaleString('zh-CN',
      {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }
  );
}

// 下一条 k 线
async function nextLine() {
	//首先获取最后一根k线的时间
	console.log('dataValue', data)
	if (data) {
		let lastTime = data.slice(-1)[0].time;
		let formattedTime = formatTime(lastTime);
		console.log('formattedTime', formattedTime);
		await axios.get('/tradingView/nextKline', {
			params: {
				interval: interval.value,
				symbol: symbol.value,
				startTime: formattedTime
			}
		}).then((res) => {
			console.log('nextKline', res.data.data)
			let item = res.data.data;
			let kline = new Kline(Number(item.o), Number(item.h), Number(item.l), Number(item.c), Date.parse(item.periodStart)/1000);

			saveDataKline(kline);
			lwChart.value.updateData(kline)
		})
	}
}

/**
 * 
 * 保存最新的 k 线
 * 
 **/
function saveDataKline(kl:Kline){
	if(data.length > 200){
		data.shift();
	}
	data.push(kl);
}

async function changeSymbol(e:any){
	symbol.value = e.target.value;
	console.log('symbol', symbol.value)
	initChart();
}

async function changeInterval(e:any){

	interval.value = e.target.value;

  let beforeDate = data.slice(0)[0].time;
  startTime.value =  formatTime(beforeDate);
  let lastTime = data.slice(-1)[0].time;
  endTime.value  = formatTime(lastTime);

  console.log('interval', interval.value)
  // console.log('startTime', startTime.value)
  console.log('endTime', endTime.value)

	initChart();
}





class Kline {
	// { open: 10, high: 10.63, low: 9.49, close: 9.55, time: 1642427876 },
	open: number;
	high: number;
	low: number;
	close: number;
	time: number;

	constructor(open: number, high: number, low: number, close: number, time: number) {
		this.open = open;
		this.high = high;
		this.low = low;
		this.close = close;
		this.time = time;
	}
}
// call a method on the component.
//   lwChart.value.fitContent();
</script>

<style scoped>
.chart-container {
	height: calc(100% - 3.2em);
}
select{
	margin-right: 1em;
	margin-bottom: 2em;
	border: 1px solid #ccc;
	border-radius: 4px;
	padding: 0.5em;
	outline: none;
}
button{
	margin-right: 1em;
	border: 1px solid #ccc;
	border-radius: 4px;
	padding: 0.5em;
	outline: none;
	background-color: #0a6358;
	cursor: pointer;
	color: #fff;
	font-size: 14px;
}
</style>